package com.sk.ccflower.lib.imgUtils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;

public class ThumbnailUtil {
	
	public static boolean thumbnailImage_JAI(String src, String dest, int width, String format) throws Exception {
		File saveFile = new File(dest);

		RenderedOp rOp = JAI.create("fileload", src);
		BufferedImage im = rOp.getAsBufferedImage();
		
		int srcWidth = im.getWidth();
		int srcHeight = im.getHeight();
		float ratio = (float) width / (float) srcWidth;
		int destWidth = width;
		int destHeight = (int) (srcHeight * ratio);
		
		BufferedImage thumb = new BufferedImage((int) destWidth, (int) destHeight, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = thumb.createGraphics();

		g2.drawImage(im, 0, 0, (int) destWidth, (int) destHeight, null);

		try {
			return ImageIO.write(thumb, format, saveFile);
		} catch ( Exception e ) {
			throw new Exception( e );
		}
	}
	
	public static boolean thumbnailImage_ImageMagick(String src, String dest, int width, int quality) throws Exception {
		if ( quality > 100 )	quality = 90;
		
		File file = new File( src );
		if ( !file.exists() )	return false;
		
		RenderedOp rOp = JAI.create("fileload", src);
		BufferedImage im = rOp.getAsBufferedImage();
		
		int srcWidth = im.getWidth();
		int srcHeight = im.getHeight();
		float ratio = (float) width / (float) srcWidth;
		int destWidth = width;
		int destHeight = (int) (srcHeight * ratio);
		String geometry = destWidth + "x" + destHeight;
		
		ArrayList<String> cmd = new ArrayList<String>();
		cmd.add( "/usr/local/bin/convert" );
		cmd.add( "-geometry" );
		cmd.add( geometry );
		cmd.add( "-quality" );
		cmd.add( quality+"" );
		cmd.add( src );
		cmd.add( dest );
		
		String[] params = (String[]) cmd.toArray( new String[1] );
		
		try {
			Process proc = Runtime.getRuntime().exec( params );
			proc.waitFor();
			return true;
		} catch ( Exception e ) {
			e.printStackTrace();
			throw e;
		}
	}
	
}
